package com.ias.agdis_r.activity.mine;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.toolbox.Volley;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListViewInterface;
import com.baoyz.swipemenulistview.SwipeMenuXListView;
import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseKeyActivity;
import com.ias.agdis_r.activity.LoginActivity;
import com.ias.agdis_r.activity.MainActivity;
import com.ias.agdis_r.activity.flight.SearchInfoActivity;
import com.ias.agdis_r.adapter.SearchDetailActivityListViewAdapter;
import com.ias.agdis_r.bean.fight.FlightQueryResult;
import com.ias.agdis_r.bean.fight.FlightQueryValue;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.ServiceManage;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.module.RestfulUri;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponseHeader;
import com.ias.agdis_r.terminalmanager.restful.flight.endpoint.request.InitFlightSubRequest;
import com.ias.agdis_r.terminalmanager.restful.flight.endpoint.response.InitFlightSubResponse;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.SecurityUtil;
import com.ias.agdis_r.util.flight.AirlineCompanyUtil;
import com.ias.agdis_r.util.flight.UiUtil;
import com.ias.agdis_r.volley.GsonRequest;
import com.ias.agdis_r.volley.callback.BaseOnVolleyErrorAdapter;
import com.ias.agdis_r.volley.callback.BaseOnVolleyErrorListener;
import com.ias.agdis_r.volley.callback.BaseOnVolleySuccessListener;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import me.maxwin.view.XListView;

public class FlightSubscribeActivity extends BaseKeyActivity implements XListView.IXListViewListener {

	private static final String MENU_STATE_CHANGE_HISTORY = DataBaseManager.getInstance().getContext().getString(R.string.changeRecord);

	private ActionBar actionBar;
	private SwipeMenuXListView mListView;
	private View viewDataEmpty;

	private Handler handler = new Handler();

	private SearchDetailActivityListViewAdapter mAdapter = null;
	/**
	 * 已订阅航班信息集合
	 */
	private List<FlightQueryValue> data = new LinkedList<FlightQueryValue>();
	private RequestQueue requestQueue;

	/**
	 * 已订阅航班列表请求成功回调
	 */
	private BaseOnVolleySuccessListener<InitFlightSubResponse> successCallback = new BaseOnVolleySuccessListener<InitFlightSubResponse>() {

		@Override
		public void onRequestSuccess(InitFlightSubResponse response) {

			data.clear();
			UiUtil.removeLoadingUiIfExist(FlightSubscribeActivity.this);

			if (response.getInitFlightSubResponseVO() == null) {
				EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, getString(R.string.noResult_2), false);

			} else {
				int num = Integer.parseInt(response.getInitFlightSubResponseVO().getNum());
				FlightQueryResult result = response.getInitFlightSubResponseVO().getResult();

				if (num > 0 && result.getFlightQueryValues().size() > 0) {
					synchronized (data) {
						data.addAll(result.getFlightQueryValues());
					}
				}
			}
			mAdapter.notifyDataSetChanged();
			onDataLoaded();

		}

		@Override
		public void onRequestFailed(BaseResponseHeader header) {
			// TODO 状态码为0的时候，服务器发现异常未返回数据
			if (data.size() > 0) {
				EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, getString(R.string.serviceError), false);
				return;
			}
			finishDelayedAfterToast(header.getErrorMessage(), 1000);
		}
	};

	/**
	 * 请求失败回调
	 */
	private BaseOnVolleyErrorListener onErrCalback = new BaseOnVolleyErrorAdapter() {
		@Override
		public void onErrorOccurred(com.android.volley.VolleyError e) {
			
			if (e instanceof TimeoutError) {
				finishDelayedAfterToast(DataBaseManager.getInstance().getContext().getString(R.string.request_err_timeout), 2000);
			} else if (e instanceof ServerError) {
				//显示接收消息异常
				finishDelayedAfterToast(DataBaseManager.getInstance().getContext().getString(R.string.request_err_servererror), 2000);
			} else if (e instanceof NoConnectionError) {
				finishDelayedAfterToast(DataBaseManager.getInstance().getContext().getString(R.string.request_err_noconnection), 2000);
			}		
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// 如果没登录
		if (!ServiceManage.getInstance().getIsLogon()) {
			gotoLoginActivity();
			finish();
			return;
		}

		setContentView(R.layout.activity_searchdetail);

		requestQueue = Volley.newRequestQueue(this);

		actionBar = getActionBar();
		initactionBar();
		initView();
		initEvent();

	}

	@Override
	protected void onResume() {
		super.onResume();
		if (ServiceManage.getInstance().getIsLogon()) {
			loadData();
			UiUtil.showLoadingUi(this);
		}
	}

	private void initEvent() {
		mListView.setXListViewListener(this);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (id < 0) {
					return;
				}
				Intent intent = new Intent(FlightSubscribeActivity.this, SearchInfoActivity.class);
				intent.putExtra(SearchInfoActivity.EXTRA_FLIGHT_SEQ, data.get((int) id).getFKE());
				intent.putExtra(SearchInfoActivity.FLIGHT_SUBSCRIBE, true);
				startActivity(intent);
			}
		});

		mListView.setOnMenuItemClickListener(new SwipeMenuListViewInterface.OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
				if(0 == index){
					Intent intent = new Intent(FlightSubscribeActivity.this, FlightStateHistoryActivity.class);
					intent.putExtra(FlightStateHistoryActivity.EXTRA_FLIGHT_FKE, "" + data.get(position).getFKE());
					startActivity(intent);
					return true;
				}
				return false;
			}
		});

//		registerForContextMenu(mListView);

		viewDataEmpty.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				UiUtil.showLoadingUi(FlightSubscribeActivity.this);
				loadData();

			}
		});

	}

	private void initView() {

		mListView = (SwipeMenuXListView) findViewById(R.id.xListView);
		viewDataEmpty = findViewById(R.id.id_data_empty);
		mListView.setPullLoadEnable(false);
		mAdapter = new SearchDetailActivityListViewAdapter(this, data);

		mListView.setEmptyView(viewDataEmpty);
		mListView.setAdapter(mAdapter);

		initSwipeMenu();

	}

	private void initSwipeMenu() {
		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				// create "open" item
				SwipeMenuItem openItem = new SwipeMenuItem(
						getApplicationContext());
				// create "delete" item
				SwipeMenuItem deleteItem = new SwipeMenuItem(
						getApplicationContext());
				// set item background
				deleteItem.setBackground(new ColorDrawable(0XFFFF0000));
				// set item width
				deleteItem.setWidth(dp2px(120));
				// set a icon
				deleteItem.setIcon(R.drawable.ic_menu_recent_history);
				// add to menu
				menu.addMenuItem(deleteItem);
			}
		};

		mListView.setMenuCreator(creator);
	}

	private int dp2px(int i) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, i, getResources().getDisplayMetrics());
	}

	/**
	 * 请求已订阅航班信息
	 */
	private void loadData() {

		InitFlightSubRequest requestBody = new InitFlightSubRequest();
		// TODO 添加服务号
		requestBody.setHeader(SecurityUtil.getCommonRequestHeaderObject(MessageModel.DYIN));

		Request<InitFlightSubResponse> request = null;
		try {
			request = new GsonRequest<InitFlightSubResponse>(
                    RestfulUri.getUri(MessageModel.DYIN), InitFlightSubResponse.class, DataManager.getInstance().getMapper().writeValueAsString(requestBody),
                    this.successCallback, this.onErrCalback);
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		requestQueue.add(request);
	}

	/**
	 * 数据加载成功后UI状态修正
	 */
	private void onDataLoaded() {
		String str = getFormatedTimeForHearder();

		Log.i("CXYU", "loaded");
		mListView.stopRefresh();
		mListView.stopLoadMore();
		mListView.setRefreshTime(str);
	}

	/**
	 * 获得当前时间的格式化字符串
	 * 
	 * @return
	 */
	@SuppressLint("SimpleDateFormat")
	private String getFormatedTimeForHearder() {
		SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
		Date curDate = new Date(System.currentTimeMillis());
		return formatter.format(curDate);
	}

	@SuppressLint("InflateParams")
	private void initactionBar() {
		actionBar.setCustomView(
				LayoutInflater.from(FlightSubscribeActivity.this).inflate(R.layout.actionbar_back_and_home, null));
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);
		TextView title = (TextView) findViewById(R.id.txt_title);
		title.setText(R.string.FlightSubscribeActivity);
		ImageView back = (ImageView) findViewById(R.id.action_back);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		ImageView home = (ImageView) findViewById(R.id.action_home);
		home.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(FlightSubscribeActivity.this, MainActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
		});
	}

	@Override
	public void onRefresh() {
		loadData();
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub

	}

	/**
	 * 显示提示信息，跳转到登录界面
	 */
	private void gotoLoginActivity() {
		EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, getString(R.string.use_function_tologin), false);
		Intent intent = new Intent(this, LoginActivity.class);
		this.startActivity(intent);
	}

	/**
	 * Toast一个消息，一段时间后退出当前Activity
	 * 
	 * @param msg 弹出消息内容
	 * @param delayedMillis 延迟时间
	 */
	private void finishDelayedAfterToast(String msg, long delayedMillis) {
		if (S.isNotEmpty(msg)) {
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, msg, false);
		}
		if (delayedMillis >= 0) {
			handler.postDelayed(new Runnable() {

				@Override
				public void run() {
					finish();
				}
			}, delayedMillis);
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
		int position = (int) adapterContextMenuInfo.id;

		// 菜单标题
		menu.setHeaderIcon(AirlineCompanyUtil.getArilineCompanyIconResourceId(data.get(position).getFLN()));
		menu.setHeaderTitle(data.get(position).getFLN());

		// 菜单选项
		menu.add(0, Integer.parseInt(data.get(position).getFKE()), 0, MENU_STATE_CHANGE_HISTORY);

	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if (item.getTitle().equals(MENU_STATE_CHANGE_HISTORY)) {
			Intent intent = new Intent(this, FlightStateHistoryActivity.class);
			intent.putExtra(FlightStateHistoryActivity.EXTRA_FLIGHT_FKE, "" + item.getItemId());
			startActivity(intent);
			return true;
		}

		return super.onContextItemSelected(item);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(null != requestQueue)
		requestQueue.stop();
	}
}
